﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Info;
using System.Security.Cryptography;
using System.Text;
using MidimediaFinder.Resources;

namespace MidimediaFinder
{
    public class Pair
    {
        public string header;
        public int val;

        public Pair(string h, int v)
        {
            header = h;
            val = v;
        }
    }

    public class SavedOptions
    {
        public bool gps = true;
        public string address = "";
        public int interval = 4;
        public int distance = 4;
        public int type = 0;
        public String email = "";
        public bool gpsPolicyAccepted = false;
        public bool notificationsEnabled = true;
        public bool isFirstStart = true;

        public SavedOptions()
        {
            gps = true;
            address = "";
            interval = 4;
            distance = 4;
            type = 0;
            email = "";
            notificationsEnabled = true;
            gpsPolicyAccepted = false;
            isFirstStart = true;
        }
    }

    public static class Storage
    {

        public static List<Pair> LoadIntervals()
        {
            var list = new List<Pair>();

            list.Add(new Pair(Strings.Interval1, 1));
            list.Add(new Pair(Strings.Interval2, 2));
            list.Add(new Pair(Strings.Interval3, 3));
            list.Add(new Pair(Strings.Interval4, 4));
            list.Add(new Pair(Strings.All, 5));

            return list;
        }

        public static List<Pair> LoadDistances()
        {
            var list = new List<Pair>();

            list.Add(new Pair(Strings.Distance1, 1));
            list.Add(new Pair(Strings.Distance2, 2));
            list.Add(new Pair(Strings.Distance3, 5));
            list.Add(new Pair(Strings.Distance4, 10));
            list.Add(new Pair(Strings.All, 100000));

            return list;
        }

        public static string CheckUtf8Chars(string s)
        {
	        if(s== null || s=="")
 			        return "";
	        s = s.Replace("\u0080","€");
	        return s;
        }

        #region SavedOptions
        
        public static SavedOptions LoadSavedOptions()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamFile = appStorage.OpenFile("SavedOptions.xml", FileMode.OpenOrCreate))
                {
                    try
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(SavedOptions));
                        using (var reader = new StreamReader(streamFile))
                            return serializer.Deserialize(reader) as SavedOptions;
                    }
                    catch (Exception) { return new SavedOptions(); }
                }
            }
        }

        public static void DeleteSavedOptions()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("SavedOptions.xml");
            }
        }

        public static void SaveSavedOptions(SavedOptions state)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("SavedOptions.xml");
                using (var streamFile = appStorage.OpenFile("SavedOptions.xml", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                //write_options_state(writer, entry);
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(SavedOptions));
                    serializer.Serialize(writer, state);
                }
            }
        }
        
        #endregion

        #region Ads

        public static List<Ads> LoadAds()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamFile = appStorage.OpenFile("ads.xml", FileMode.OpenOrCreate))
                {
                    try
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<Ads>));
                        using (var reader = new StreamReader(streamFile))
                            return serializer.Deserialize(reader) as List<Ads>;
                    }
                    catch (Exception) { return new List<Ads>(); }
                }
            }
        }

        public static void DeleteAds()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("ads.xml");
            }
        }

        public static void SaveAds(List<Ads> list)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("ads.xml");
                using (var streamFile = appStorage.OpenFile("ads.xml", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                //write_options_state(writer, entry);
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Ads>));
                    serializer.Serialize(writer, list);
                }
            }
        }

        #endregion

        public static void getHTML(string query, string options, Action<string> callback, Action<string, string> callback2, Action error)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            objs = new StreamReader(objResponse.GetResponseStream());

                            var s = objs.ReadToEnd();
                            if (callback2 != null)
                                callback2(s, options);
                            else if (callback != null)
                                callback(s);

                            return;
                        }
                        catch (Exception e)
                        {
                            e.ToString();
                            error();
                        }
                    }
                    , req);
            }
            catch (Exception)
            {
                error();
            }
        }
        public static void getHTML(string query, Action<string> callback, Action<Exception> error)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            objs = new StreamReader(objResponse.GetResponseStream());

                            var s = objs.ReadToEnd();
                            if (callback != null)
                                callback(s);

                            return;
                        }
                        catch (Exception e)
                        {
                            e.ToString();
                            error(e);
                        }
                    }
                    , req);
            }
            catch (Exception e)
            {
                error(e);
            }
        }
        public static void getHTML(string query, Action<string> callback, Action error)
        {
            getHTML(query, "", callback, null, error);
        }


        public static void getHTML(string query, string options, Action<string, string> callback, Action error)
        {
            getHTML(query, options, null, callback, error);
        }


        #region utilizations
        public static string GetUtilizationUrl(bool isTrial)
        {
            return GetUtilizationUrl(0, isTrial);
        }
        public static string GetUtilizationUrl(int occ, bool isTrial)
        {
            var s = "http://fboscari.altervista.org/submit_Utilizzi.php?name=" +
                Strings.Title +
                (isTrial ? " Trial" : "") +
                "&id=" +
                getID();
            if (occ >= 1)
                s += "&occ=" +
                    occ;
            return s;

        }
        public static string getID()
        {
            byte[] result = null;
            object uniqueId;
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
                result = (byte[])uniqueId;
            var s = "";
            for (int i = 0; i < result.Length; i++)
                s += result[i];
            return s;
        }



        private static Func<StreamReader, int> read_utilizations = reader =>
        {

            var s = reader.ReadToEnd();
            var occ = Int16.Parse(s);


            return occ;
        };


        private static Action<StreamWriter, int> write_utilizations = (writer, occ) =>
        {
            var s = "" + occ;

            writer.Write(s);
        };



        public static void SaveUtilizations(int utilizations)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("utilizations.txt");
                using (var streamFile = appStorage.OpenFile("utilizations.txt", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                    write_utilizations(writer, utilizations);
            }
        }



        public static void DeleteUtilizations()
        {
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            appStorage.DeleteFile("utilizations.txt");
        }

        public static int LoadUtilizations()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamFile = appStorage.OpenFile("utilizations.txt", FileMode.OpenOrCreate))
                {
                    try
                    {
                        using (var reader = new StreamReader(streamFile))
                            return read_utilizations(reader);
                    }
                    catch (Exception)
                    {
                        appStorage.DeleteFile("utilizations.txt");
                        return 0;
                    }
                }


            }

        }
        #endregion

        #region Share

        public static string  ComposeHeader()
        {
	        var s="";
	        s = Strings.Sendby + " " + Strings.Title;
	        return s;
        }

        public static string  ComposePoiEmail(item item)
        {
	        return ComposePoiEmail(item, true);
        }

        public static string  ComposePoiEmail(item item, bool header)
        {
	        var s="";
	        if(header==true)
		        s=ComposeHeader();

            s += "\n\n" + Strings.Name + " " + item.Name + "\n\n";
            s += Strings.Type + " " + item.Type_Name + "\n";
            s += Strings.Address + " " + item.Adress + "\n";
            s += Strings.MapAndDirections + " " + item.Map + "\n\n";
	
	        if(item.Website!=null && item.Website!="")
                s += Strings.Website + " " + item.Website + "\n";
	        if(item.Email!=null && item.Email!="")
                s += Strings.Email + " " + item.Email + "\n";
	        if(item.PhoneNumber!=null && item.PhoneNumber!="")
                s += Strings.PhoneNumber + " " + item.PhoneNumber + "\n\n";
	
	        if(item.FBName!=null && item.FBName!="")
                s += Strings.Facebook + " " + item.FBName + "\n";
	        if(item.FBUrl!=null && item.FBUrl!="")
                s += Strings.FacebookProfile + " " + item.FBUrl + "\n";
	
	        if(item.TwitterName!=null && item.TwitterName!="")
                s += Strings.Twitter + " " + item.TwitterName + "\n";
	        if(item.TwitterUrl!=null && item.TwitterUrl!="")
                s += Strings.TwitterChannel + " " + item.TwitterUrl + "\n";
	
	        if(item.Description!=null && item.Description!="")
                s += Strings.Description + " " + item.Description + "\n";
	
	        if(header==true)
		        s+="\n\n\n" + Strings.Footer;
	        return s;
        }

        public static string  ComposePromotionEmail(promotion item)
        {
	        var s=ComposeHeader();

            s += "\n\n" + Strings.Promotion + ":\n\n";
	
	        if(item.Short_description!=null && item.Short_description!="")
                s += Strings.Description + " " + item.Short_description + "\n\n";
	
	        if(item.Hint!=null && item.Hint!="")
                s += Strings.Hint + " " + item.Hint + "\n\n";

            s += Strings.StartDate + " " + item.StartDate + "\n";
            s += Strings.StartTime + " " + item.StartTime + "\n\n";

            s += Strings.EndDate + " " + item.EndDate + "\n";
            s += Strings.EndTime + " " + item.EndTime + "\n\n";
	
	        if(item.Promotion_Description!=null && item.Promotion_Description!="")
                s += Strings.Description + " " + item.Promotion_Description + "\n\n";

	        if(item.Bonus=="1")
		        s+=Strings.Bonus + ": " + Strings.Yes + "\n";
	
	        if(item.Bonus=="1" && item.Bonus_desc!=null && item.Bonus_desc!="")
                s += Strings.Bonus_desc + " " + item.Bonus_desc + "\n\n";

	
	        s+="\n  -  \n\n";
	        s+=Strings.Promoter + ":\n\n";
	
	        s += ComposePoiEmail(item, false);
	
	        s+="\n\n\n" + Strings.Footer;
	
	        return s;
        }


        public static string ComposePoiSMS(item item)
        {
            return ComposePoiSMS(item, true);
        }

        public static string ComposePoiSMS(item item, bool header)
        {
            var s = "";
            if (header == true)
                s = ComposeHeader();

            s += "\n"+Strings.Name +" " + item.Name + "\n";
            s += Strings.Type + " " + item.Type_Name + "\n";
            s += Strings.Address + " " + item.Adress + "\n";
            
            if (header == true)
                s += "\n" + Strings.Footer;
            return s;
        }

        public static string ComposePromotionSMS(promotion item)
        {
            var s = ComposeHeader();

            s += "\n" + Strings.Promotion + ":\n";

            if (item.Short_description != null && item.Short_description != "")
                s += Strings.Description + " " + item.Short_description + "\n";

            if (item.Hint != null && item.Hint != "")
                s += Strings.Hint + " " + item.Hint + "\n";

            

            s += "\n"+Strings.Promoter + ":";

            s += ComposePoiSMS(item, false);

            s += "\n" + Strings.Footer;

            return s;
        }
        #endregion
    }
}
